package com.itcm.skymail.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcm.common.constant.ProductConstant;
import com.itcm.common.utils.PageUtils;
import com.itcm.common.utils.Query;
import com.itcm.skymail.product.dao.AttrGroupDao;
import com.itcm.skymail.product.entity.AttrAttrgroupRelationEntity;
import com.itcm.skymail.product.entity.AttrEntity;
import com.itcm.skymail.product.entity.AttrGroupEntity;
import com.itcm.skymail.product.service.AttrAttrgroupRelationService;
import com.itcm.skymail.product.service.AttrGroupService;
import com.itcm.skymail.product.service.AttrService;
import com.itcm.skymail.product.service.ProductAttrValueService;
import com.itcm.skymail.product.vo.AttrGroupWithAttrVo;
import com.itcm.skymail.product.vo.SpuItemBaseAttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private AttrAttrgroupRelationService relationService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Override

    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.eq("attr_group_id", key).or().like("attr_group_name", key);
        }
        if (catelogId != 0) {
            wrapper.and((obj) -> {
                obj.eq("catelog_id", catelogId);
            });
        }
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public List<AttrEntity> getRelationListByGroupId(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> relationEntities = relationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrIds = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        List<AttrEntity> attrEntities = attrService.listByIds(attrIds);
        return attrEntities;
    }

    @Transactional
    @Override
    public void removeCasByIds(List<Long> ids) {
        // 删除属性分组表数据
        this.removeByIds(ids);
        // 删除关联信息表
        relationService.remove(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", ids));
    }

    @Override
    public void deleteRalation(List<AttrAttrgroupRelationEntity> relationEntities) {
//        List<Long> attrIds = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
//
//        // 因为是一对多关系 所以只需要根据attrId删除即可
//        relationService.remove(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_id", attrIds));
        // 这是适用于多对多关系的 拼接sql的写法
        relationService.deleteBatchRelation(relationEntities);
    }

    // 获取当前分类 可关联还未关联的属性列表 （基本属性 非销售属性）
    @Override
    public PageUtils queryNoRelationPage(Map<String, Object> params, Long attrgroupId) {
        // 1、 根据属性分组ID 获取分类ID
        // 2、 首先获取当前分类下的所有基本属性（规格参数）
        // 3、 再排除已经被其他分组绑到过的属性

        AttrGroupEntity attrGroup = this.getById(attrgroupId);
        Long catelogId = attrGroup.getCatelogId();

        List<AttrAttrgroupRelationEntity> relationEntities = relationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>());
        // 已经关联过的属性集合
        Set<Long> relationedAttrIds = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toSet());

        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId);

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.like("attr_name", key);
        }

        if (relationedAttrIds.size() > 0) {
            wrapper.and(obj -> {
                obj.notIn("attr_id", relationedAttrIds);
            });
        }

        wrapper.and(obj -> {
            obj.eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        });


        IPage<AttrEntity> page = attrService.page(new Query<AttrEntity>().getPage(params), wrapper);

        PageUtils pageUtils = new PageUtils(page);

        return pageUtils;
    }

    @Override
    public void batchSaveRelation(List<AttrAttrgroupRelationEntity> relationEntities) {
        relationService.saveBatch(relationEntities);
    }

    @Override
    public List<AttrGroupWithAttrVo> getGroupsWithAttrByCatId(Long catelogId) {
        List<AttrGroupEntity> attrGroupEntities = this.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        if (attrGroupEntities.size() == 0) {
            return null;
        }
        return attrGroupEntities.stream().map(attrGroup -> {
            AttrGroupWithAttrVo attrGroupWithAttrVo = new AttrGroupWithAttrVo();
            BeanUtils.copyProperties(attrGroup, attrGroupWithAttrVo);
            List<AttrEntity> attrEntities = this.getRelationListByGroupId(attrGroup.getAttrGroupId());
            attrGroupWithAttrVo.setAttrs(attrEntities);
            return attrGroupWithAttrVo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<SpuItemBaseAttrVo> getBaseAttrsWithGroup(Long spuId, Long catalogId) {
        return this.baseMapper.getBaseAttrsWithGroup(spuId, catalogId);
    }
}